package idea.innovacion.dao;

import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import idea.innovacion.interfaces.DAOExcepcion;
import idea.innovacion.util.ConexionBD;
import idea.innovacion.bean.UsuarioDTO;



public class MySqlUsuario2DAO extends BaseDAO {
	
	// Insertar
	
	public UsuarioDTO insertar(UsuarioDTO dto) throws DAOExcepcion
	{
		String sqlQuery;
		sqlQuery = "Insert into Usuario (Nombre, ApellidoPaterno,ApellidoMaterno,Sexo,TipoDocumento, NumeroDocumento, Email, Celular, Clave, IdPerfil,Rol ) values (?,?,?,?,?,?,?,?,?,?,?)";
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = ConexionBD.obtenerConexion();
			
			stmt = con.prepareStatement(sqlQuery);
			stmt.setString(1, dto.getNombre());
			stmt.setString(2, dto.getApellidoPaterno());
			stmt.setString(3, dto.getApellidoMaterno());
			stmt.setString(4, dto.getSexo());
			stmt.setString(5, dto.getTipoDocumento());
			stmt.setInt(6, dto.getNumeroDocumento());
			stmt.setString(7, dto.getEmail());
			stmt.setInt(8, dto.getCelular());
			stmt.setString(9, dto.getClave());
			stmt.setInt(10, dto.getIdPerfil());
			stmt.setString(11, dto.getRol());
			
			
			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("No se pudo insertar");
			}
			
			// Obtener el ultimo id
			int id = 0;
			sqlQuery = "SELECT LAST_INSERT_ID()";
			stmt = con.prepareStatement(sqlQuery);
			rs = stmt.executeQuery();
			if (rs.next()) {
				id = rs.getInt(1);
			}
			dto.setIdUsuario(id);
			
			
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return dto;

	}

}
